﻿using System;

namespace Vessel_calculation.Classes
{
	/// <summary>
	/// Description of Ship.
	/// </summary>
	public class Ship
	{
		public Ship_Parameters parameters;
		public Point<double>[,] drawing;
		public int waterlines, bends;
		public int k;					//Count of middle bend
		public double[] kb, ks;
		
		public double[] S, My, Ix, Iy, xf, Iyf;
		public double[] V, xc, zc, R, r, zm;
		
		public Ship()
		{
		}
		
		public void HydrostaticCalc()
		{
			k = bends / 2;
			BowCoeffCalc();
			Hydrostatic();
			VolCalc();
		}
		
		private void BowCoeffCalc()
		{
			for (int i=0; i < bends; i++)
			{
				for (int j=0; j < waterlines; j++)
				{
					if (drawing[i,j].y < 0 && i < k)
					{
						drawing[i,j].y = 0;
						drawing[i+1,j].y *= kb[j];
					}
					if (i == 0)
					{
						drawing[i,j].y *= kb[j];
					}
					if (drawing[i,j].y < 0 && i > k)
					{
						drawing[i,j].y = 0;
						drawing[i-1,j].y *= ks[j];						
					}
					if (i == bends-1)
					{
						drawing[i,j].y *= ks[j];
					}
				}
			}
		}
		
		private void Hydrostatic()
		{
			S = new double[waterlines];
			My = new double[waterlines];
			Ix = new double[waterlines];
			Iy = new double[waterlines];
			xf = new double[waterlines];
			Iyf = new double[waterlines];
			
			double dL = drawing[0,0].x - drawing[1,0].x;
			
			for (int j=0; j < waterlines; j++)
			{
				for (int i=0; i < bends; i++)
				{
					S[j] += drawing[i,j].y;
					My[j] += drawing[i,j].y*(k-i);
					Ix[j] += Math.Pow(drawing[i,j].y, 3);
					Iy[j] += Math.Pow((k-i), 2)*drawing[i,j].y;
				}
				S[j] *= 2*dL;
				My[j] *= 2*Math.Pow(dL, 2);
				Ix[j] *= 2*dL/3;
				Iy[j] *= 2*Math.Pow(dL, 3);
				xf[j] = My[j]/S[j];
				Iyf[j] = Iy[j] - S[j]*Math.Pow(xf[j], 2);
			}
		}
		
		private void VolCalc()
		{
			V = new double[waterlines];
			xc = new double[waterlines];
			zc = new double[waterlines];
			R = new double[waterlines];
			r = new double[waterlines];
			zm = new double[waterlines];
					
			V[0] = xc[0] = zc[0] = 0;
			
			for (int i=1; i < waterlines; i++)
			{
				V[i] = V[i-1] + S[i-1] + S[i];
				xc[i] = xc[i-1] + My[i-1] + My[i];
				zc[i] = zc[i-1] + (i-1)*S[i-1] + i*S[i];
			}
			xc[0] = xf[0];
			for (int i=1; i < waterlines; i++)
			{
				V[i] *= (drawing[k,i].z-drawing[k,i-1].z)/2;
				xc[i] *= (drawing[k,i].z-drawing[k,i-1].z)/(V[i]*2);
				zc[i] *= Math.Pow((drawing[k,i].z-drawing[k,i-1].z),2)/(V[i]*2);
			}
			for (int i=1; i < waterlines; i++)
			{
				R[i] = Iyf[i]/V[i];
				r[i] = Ix[i]/V[i];
				zm[i] = zc[i] + r[i];
			}
		}
	}
}
